package org.dy.db.support;

import java.util.List;
import java.util.Map;

import org.dy.db.Page;

public class QueryCachedDAO extends BaseDAO {
	
	private CacheManager cacheManager;
	
	public QueryCachedDAO(int refreshPeriod) {
		super();
		initCache(refreshPeriod);
	}

	private void initCache(int refreshPeriod) {
		cacheManager = CacheManager.getInstance(refreshPeriod);
	}

	private String getCacheKey(String sql, Object[] args){
		StringBuffer sb = new StringBuffer();
		sb.append("sql-");
		sb.append(sql);
		sb.append("||");
		if(args != null){
			for(Object obj:args){
				sb.append(obj);
				sb.append(",");
			}
		}
		return sb.toString();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Map> queryForList(String sql, Object[] args) {
		String key = getCacheKey(sql, args);
		
		List<Map> list = (List<Map>) cacheManager.getCache().get(key);
		if(list == null){
			list = super.queryForList(sql, args);
			cacheManager.getCache().put(key, list);
		}

		return list;
	}
	
	@Override
	public Map queryForMap(String sql, Object[] args) {
		String key = getCacheKey(sql, args);
		
		Map map = (Map) cacheManager.getCache().get(key);
		if(map == null){
			map = super.queryForMap(sql, args);
			cacheManager.getCache().put(key, map);
		}

		return map;
	}
	
	@Override
	public Page queryForPage(String sql, Object[] args, int cp, int npp) {
		String key = getCacheKey(sql, args);
		key += ("||" + cp + "," + npp);
		
		Page page = (Page) cacheManager.getCache().get(key);
		if(page == null){
			page = super.queryForPage(sql, args, cp, npp);
			cacheManager.getCache().put(key, page);
		}

		return page; 
	}

}
